#   Copyright 2006 Jerome Lacoste (jerome@coffeebreaks.org)
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
class ClientsController < ApplicationController

  before_filter :authorize

  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @client = Client.new
    @client.owner_id = session[:user_id]
    
    owner = User.find(session[:user_id])
    # FIXME sorting doesn't work here
    @sorter = SortingHelper::Sorter.new self, %w(name short url), @params['sort'], @params['order'], 'name', 'ASC'
#    @client_pages, @clients = pagination owner.clients, @sorter.to_sql
    @client_pages, @clients = pagination Client.find_all_by_owner_id( @client.owner_id, @sorter.to_sql)
  end

#  def new
#    @client = Client.new
#    @client.owner_id = session[:user_id]
#  end

  def create
    @client = Client.new(params[:client])
    if @client.save
      flash[:notice] = 'Client was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def tracker_edit
    @client = Client.find(params[:id])
    @trackers = IssueTracker::Tracker.supported_tracker_names
    @tracker = @client.tracker || Tracker.new
    if request.post?
      @tracker.attributes = params[:tracker]
      # FIXME can't I just save the client ??
      if @tracker.save
        @client.tracker_id = @tracker.id
        @client.save
        flash[:notice] = 'Client Tracker was successfully updated.'
        redirect_to :action => 'tracker_edit', :id => @client
      else
        render :action => 'tracker_edit'
      end
    end
  end

  def tracker_delete
    @client = Client.find(params[:id])
    @client.tracker_id = nil
    # FIXME can't I just save the client ?
    @client.tracker.destroy
    @client.save
    flash[:notice] = 'Client Tracker was deleted.'
    redirect_to :action => 'edit', :id => @client
  end

  def edit
    @client = Client.find(params[:id])
  end

  def update
    @client = Client.find(params[:id])
    if @client.update_attributes(params[:client])
      flash[:notice] = 'Client was successfully updated.'
      redirect_to :action => 'edit', :id => @client
    else
      render :action => 'edit'
    end
  end

  def destroy
    Client.find(params[:id]).destroy
    redirect_to :action => 'list'
  end
end
